function cmfunc(varargin)
%CMFUNC(FUNC_NAME) create matlab function
%   CMFUNC(FUNC_NAME) create a function with a template
%   
%   Inputs:
%     func_name   the m-function file name
%
%   Example:
%     cmfunc('demo')  create a demo m-function with template and save it as
%                     demo.m in current path
%

% Author: Xiaobiao Huang
% Copyright 2013-2020 Xiaobiao Studio.
% $Revision: 1.0.0.0 $  $Date: 2013-06-25 20:51:32 $

if length(varargin) < 1
  disp('not enough inputs');
  return;
end
  % get the template path
  theFilePath = fileparts(which(mfilename('fullpath')));
  fid = fopen(fullfile(theFilePath,'template\mtemplate.m'));
  try
    line = fgetl(fid);
    str = cell(0);
    count = 1;
    while ischar(line)
      str{count} = [line,'\n'];
      line = fgetl(fid);
      count = count+1;
    end
    fclose(fid);
  catch err
      fclose(fid);
      rethrow(err);
  end
  str = [str{:}];
  
  str = strrep(str,'$func_name_desc',upper(varargin{1}));
  str = strrep(str,'$func_name',varargin{1});
  str = strrep(str,'$date',datestr(clock));
  
  newfid = fopen([varargin{1} '.m'],'w');
  try
    fprintf(newfid,str);
    if newfid > 2
      fclose(newfid);
    end
  catch err
    if newfid > 2
      fclose(newfid);
    end
    rethrow(err);
  end
  open([varargin{1} '.m']);
end